﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SimpleAppServer.Core;
using System.IO.Ports;

namespace SimpleAppServer.Implement.SerialPort
{
    /// <summary>
    /// SerialPort服务器
    /// </summary>
    public class SerialPortServer : AbstractAppServer
    {

        bool m_IsRunning = false;
        /// <summary>
        /// 是否运行中
        /// </summary>
        public override bool IsRunning
        {
            get {
                return m_IsRunning;
            }
        }

        SerialPortConfig m_Config = null;
        bool m_Setuped = false;
        /// <summary>
        /// 安装配置
        /// </summary>
        /// <param name="config">配置</param>
        public override void Setup(IServerConfig config)
        {
            m_Config = config as SerialPortConfig;
            if (m_Config == null)
            {
                throw new ArgumentException("SerialPortConfig");
            }
            m_Setuped = true;
        }

        System.IO.Ports.SerialPort m_Server = null;
        /// <summary>
        /// 开启服务
        /// </summary>
        /// <returns>开启成功或失败</returns>
        public override bool Start()
        {
            if (!m_Setuped)
            {
                throw new Exception("尚未调用SteUp安装服务器配置.");
            }
            try
            {
                m_Server = new System.IO.Ports.SerialPort(m_Config.CommName,
                    m_Config.BaudRate,
                    m_Config.Parity,
                    m_Config.Bits,
                    m_Config.Stop);
                m_Server.Open();
                if (m_Server.IsOpen)  //Opened
                {
                    m_Server.DataReceived += new SerialDataReceivedEventHandler(SerialPort_DataReceived);
                }
                else
                {
                    return false;  //Error
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return false;
            }
            m_IsRunning = true;
            return true;
        }

        /// <summary>
        /// SerialPort数据接收事件绑定方法
        /// </summary>
        /// <param name="sender">SerialPort</param>
        /// <param name="e">SerialDataReceivedEventArgs</param>
        void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (m_IsRunning)
            {
                System.IO.Ports.SerialPort serial = (System.IO.Ports.SerialPort)sender;
                if (serial.BytesToRead > 0)
                {
                    byte[] buff = new byte[serial.BytesToRead];
                    serial.Read(buff, 0, buff.Length);
                    OnReceived(new ReceivedArgs(new SerialPortSession(m_Server), buff));
                }
            }
        }

        /// <summary>
        /// 创建SerialPortSession
        /// </summary>
        /// <param name="token">设置为Null</param>
        /// <returns>SerialPortSession</returns>
        public override IAppSession CreateSession(object token=null)
        {
            if (!m_IsRunning)
            {
                throw new NotSupportedException("服务器尚未运行.");
            }
            return new SerialPortSession(m_Server);
        }

        /// <summary>
        /// 结束服务
        /// </summary>
        public override void End()
        {
            try
            {
                m_IsRunning = false;
                if (m_Server.IsOpen)
                {
                    m_Server.Close();
                    m_Server.Dispose();
                    m_Server = null;
                }
            }
            catch (Exception ex)
            {
                logger.Debug(ex);
            }
        }
    }
}
